﻿using MixerReport.Commands;
using MixerReport.Models;
using MixerReport.Objects;
using hyjx;
using hyjx.bind;
using Hyjx.GF.Database;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Media3D;

namespace MixerReport.ViewModels
{
    internal class ReportPageViewModel : BindableBase
    {
        public ReportPageViewModel()
        {

        }
        /// <summary>
        /// 过滤器
        /// </summary>
        public FilterModel Filter { get; } = new();
        /// <summary>
        /// 粉体报表集
        /// </summary>
        public ObservableCollection<ReportObject> Reports { get; } = new();
        /// <summary>
        /// 分页器
        /// </summary>
        public PagorModel Pagor { get; } = new();

        private bool _isIdle = true;
        /// <summary>
        /// 是否空闲
        /// </summary>
        public bool IsIdle { get => _isIdle; set => SetProperty(ref _isIdle, value); }

        Visibility _isExporting = Visibility.Collapsed;
        /// <summary>
        /// 是否正在导出
        /// </summary>
        public Visibility IsExporting { get => _isExporting; set => SetProperty(ref _isExporting, value); }

        public ExportCommand ExportCommand { get; } = new();

        public void Page_Loaded(object sender, RoutedEventArgs e)
        {
            Filter.StartDate = DateTime.Now.AddDays(-1);
            Filter.EndDate = DateTime.Now;
            Filter.FilterCommand.Execute(this);
        }
        internal IQueryable<MixerDataReportEntity>? GetAllReports()
        {
            if (string.IsNullOrEmpty(App.DbConnectionString)) return null;

            GFDbContext db = new(App.DbConnectionString);
            if (db.MixerDataReports == null)
            {
                MessageBox.Show("搅拌机数据报表不存在。", "数据库错误", MessageBoxButton.OK, MessageBoxImage.Error);
                Application.Current.Shutdown(0);
                return null;
            }

            // 筛选
            IQueryable<MixerDataReportEntity> query = db.MixerDataReports.AsQueryable();

            if (!string.IsNullOrEmpty(Filter.SelectedMixerName.Key))
                query = query.Where(p => p.DeviceName == Filter.SelectedMixerName.Value);

            //if (Filter.SelectedMaterial.Key != MixerReportConstants.Eng_All)
            //    query = query.Where(p => p.Material == Filter.SelectedMaterial.Key);

            if (Filter.StartDate != null)
                query = query.Where(p => p.RecordTime >= Filter.StartDate);

            if (Filter.EndDate != null)
                query = query.Where(p => p.RecordTime <= Filter.EndDate);

            // 排序
            query = LambdaHelper.Orderby(query, Filter.SelectedSortField.Key, Filter.SelectedOrderByField.Key);

            return query;
        }

        internal void GetReports()
        {
            if (App.Materials == null)
                return;

            IsIdle = false;
            Pagor.RaiseCommandsCanExecute();
            Filter.FilterCommand.OnCanExecuteChanged();

            IQueryable<MixerDataReportEntity>? query = GetAllReports();
            if (query == null)
                return;

            // 设置分页器
            Pagor.EntryAmount = query.Count();
            Pagor.TotalPage = (int)Math.Ceiling((decimal)Pagor.EntryAmount / Pagor.SelectedPageRows.Key);

            // 分页
            query = query.Skip((Pagor.CurrentPageNumber - 1) * Pagor.SelectedPageRows.Key).Take(Pagor.SelectedPageRows.Key);

            // 呈现
            Reports.Clear();
            query.ToList().ForEach(p =>
            {
                Reports.Add(new ReportObject(p.DeviceName, p.Material, p.RecordTime, p.Step, p.ElapsedTime, p.RemainTime, p.StirRotateSpeed, p.StirRotateActualSpeed, p.ScatteredRotateSpeed, p.ScatteredRotateActualSpeed, p.Temperature, p.ActualTemperature, p.Pressure, p.ActualPressure, p.MaterialWeight, p.MaterialActualWeight, p.StirCurrent, p.ScatteredCurrent, p.ReturnWaterTemperature));
            });

            if (!Reports.Any())
                Pagor.CurrentPageNumber = 0;

            IsIdle = true;
            Pagor.RaiseCommandsCanExecute();
            Filter.FilterCommand.OnCanExecuteChanged();
            ExportCommand.OnCanExecuteChanged();
        }
    }
}
